package com.qf.microuser.point.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.common.core.entity.PointRule;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.microuser.point.mapper.PointRuleMapper;
import com.qf.microuser.point.service.PointRuleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * --- 缘分让我们相遇乱世以外 ---
 *
 * @author SJY
 * 2024/12/30
 * 因为这个数据不常变,所以可以缓存到redis中,提高查询效率
 * 积分规则缓存到redis中
 */
@Service
public class PointRuleServiceImpl implements PointRuleService {
    @Resource
    private PointRuleMapper pointRuleMapper;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public PointRule pointRuleByType(Integer pointType) {
        // 先查询缓存,如果数据存在,则直接返回,如果不存在,则查询数据库,并缓存到redis中
        // 使用string 类型存储缓存数据,key为pointType,value为序列化后的PointRule对象
        List<PointRule> pointRuleList = redisUtil.getCacheObject("point:rule");
        if (pointRuleList == null){
            pointRuleList = pointRuleMapper.selectList(null);
            redisUtil.setCacheObject("point:rule",pointRuleList,60*60*24*30, TimeUnit.SECONDS);
        }

        return pointRuleList.stream()
                .filter(item -> item.getPointType().equals(pointType))
                .findFirst().orElse(null);

        // return pointRuleMapper.selectOne(new LambdaQueryWrapper<PointRule>()
        //         .eq(PointRule::getPointType,pointType));
    }

    @Override
    public PointRule addPointRule(PointRule pointRule) {
        return pointRuleMapper.selectOne(new LambdaQueryWrapper<PointRule>()
                .eq(PointRule::getPointType,pointRule.getPointType()));
    }

}
